package com.common.www.aop.resolver;


import com.common.www.service.auth.UserService;
import com.common.www.bean.entity.auth.BaseUserInf;
import com.common.www.bean.vo.UserVo;
import com.common.www.config.WebConfig;
import com.common.www.utils.TxtUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * @Description 登录用户的参数解析器，将含有 @LoginUser 注解的方法参数注入当前登录用户
 * @Author luozisong
 * @Version 1.0
 **/
public class SysUserArgumentResolver implements HandlerMethodArgumentResolver {

    private static final Logger LOGGER = LoggerFactory.getLogger(SysUserArgumentResolver.class);

    /**
     * redis 相关
     */
    @Autowired
    UserService userService;

    /**
     * 返回true时才会执行下面的resolveArgument方法
     *
     * @param parameter
     * @return
     */
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        //判断是否是某个类的父类
        return BaseUserInf.class.isAssignableFrom(parameter.getParameterType()) && parameter.hasParameterAnnotation(CurrentUser.class);
    }

    /**
     * 获取用户信息并返回
     *
     * @param parameter
     * @param mavContainer
     * @param webRequest
     * @param binderFactory
     * @return 返回用户信息
     * @throws Exception
     */
    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        System.out.println(parameter);
        String token = webRequest.getHeader(WebConfig.Token);
        if (TxtUtil.isEmpty(token)) {
            String id = webRequest.getAttribute(WebConfig.ACCOUNT_KEY,0)+"";
            return null;
        }

        if (TxtUtil.isEmpty(token)) {

            return null;
        }
        UserVo user = userService.getUserVoFromRedis(token);
        return user;
    }
}
